package com.iscc.fake.controller;

import com.google.gson.Gson;
import com.iscc.fake.domain.Product;
import com.iscc.fake.service.Impl.ProductServiceImpl;
import com.iscc.fake.service.ProductService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet({"/query_all_product.do","/query_type_id.do"})
public class ProductSreachServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
         doPost(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        ProductService productService = new ProductServiceImpl();
        PrintWriter out = response.getWriter();
        Gson gson = new Gson();
        String uri = request.getRequestURI();
        Map<String, Object> resultMap = new HashMap<>();
        if (uri.endsWith("/query_all_product.do")) {
            String name = request.getParameter("pname");
            List<Map<String, Object>> list = productService.queryAllProduct(name);
            if (list.size() > 0) {
                resultMap.put("code", 200);
                resultMap.put("msg", "查询商品成功");
                resultMap.put("result", list);
            } else {
                resultMap.put("code", 201);
                resultMap.put("msg", "查询商品成功,暂无数据");
            }
        }else if(uri.endsWith("/query_type_id.do")){
            int pno = Integer.parseInt(request.getParameter("pno"));
            Product product=productService.queryByid(pno);
            resultMap.put("product",product);
        }
        String resultStr = gson.toJson(resultMap);
        out.print(resultStr);
    }
}
